package org.skydiveapphd;

import org.skydiveapphd.ui.FragmentHelper;
import org.skydiveapphd.interfaces.AircraftNotifier;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.repository.AircraftRepository;
import org.skydiveapplibrary.ui.AircraftSelectListAdapter;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class AircraftSelectListActivity extends BaseListFragment
{	
	public static AircraftSelectListActivity newInstance(Bundle args) 
	{
		AircraftSelectListActivity f = new AircraftSelectListActivity();
		f.setArguments(args);
		return f;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    }
    
	@Override
	public void onResume()
	{
		super.onResume();

		// init view
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		setHeaderText(R.string.select_aircraft_label);
		
		loadData();
		
		setBottomButtonVisibility(View.GONE);
	}
    
	@Override
	protected void onTopButtonClick()
	{
		FragmentHelper.getInstance().openFragment(AircraftEditActivity.newInstance(new Bundle()), android.R.id.tabhost, 
				Constants.TAG_AIRCRAFT_EDIT, getFragmentManager());
    }
    
    @Override
	public void onListItemClick(ListView listView, View view, int indx, long id)
    {
		// get current selection
    	int previousSelectedId = getArguments().getInt(Constants.EXTRA_AIRCRAFT_ID, -1);
    	int newSelectedId = (int)id;
    	
    	// if different than previous  	
		AircraftNotifier f = (AircraftNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
		
		if (previousSelectedId != newSelectedId)
			f.updateAircraft(newSelectedId);
		
		getFragmentManager().popBackStack();
    }
    
    private void loadData()
    {
    	// populate aircrafts
		AircraftRepository repository = new AircraftRepository(getActivity());
		AircraftSelectListAdapter adapter = new AircraftSelectListAdapter(
				getActivity(),
				repository.getAircrafts());
		setListAdapter(adapter);
		
		// set initial selection
		int selectedId = getArguments().getInt(Constants.EXTRA_AIRCRAFT_ID, -1);
		for (int index = 0; index < adapter.getCount(); index++)
		{
			getListView().setItemChecked(index,
					adapter.getItems().get(index).getId() == selectedId); 
		}
    }
} 